package files_handler;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import dropbox.common.Utils;
import serverDB_classes.DBManager;

/**
 * manage files PHYSICALLY written on server
 * 
 * --Singleton--
 * 
 * @author Yoav
 * 
 */

public class FilesManager {
	// saving dir on server
	private String savingDir;

	// --Singleton implementation--//
	private static class FilesManagerHolder {
		static final FilesManager filesManagerHolder = new FilesManager();
	}

	// constructor
	private FilesManager() {
		savingDir = "C:\\temp\\server";
	}

	/**
	 * get FilesManager instance
	 * 
	 * @return FilesManager instance
	 */
	public static FilesManager getFilesManager() {
		return FilesManagerHolder.filesManagerHolder;
	}

	/**
	 * check if file exists on server
	 * 
	 * @param checkSum - checkSum of a file
	 * @return true if exists on server false OW
	 */
	public boolean isExists(String checkSum) {
		return DBManager.getDBManager().isFileExists(checkSum);
	}

	/**
	 * save a file on server
	 * 
	 * @param file - file to save on server
	 * @return file's checkSum
	 * @throws IOException if file can't be moved 
	 * 					to saving dir location from temp location
	 */
	public String saveFile(File file) throws IOException {

		//get file's checkSum
		String checkSum = Utils.getCheckSum(file);		
		//get dir's path
		Path targetPath = Paths
				.get(savingDir + System.getProperty("file.separator") + String.valueOf(checkSum));
		//check if file dosen't exist on saving location
		if (!Files.exists(targetPath, LinkOption.NOFOLLOW_LINKS)) {
			//move file from temp location to saving dir
			Files.move(file.toPath(), targetPath,
					StandardCopyOption.REPLACE_EXISTING);
			//update new checkSum in data base
			DBManager.getDBManager().newCheckSum(checkSum);
		} else {			
			file.delete();
		}
		return checkSum;
	}

	/**
	 * get a physically file on disk by checkSum
	 * @param checkSum - file's checkSum
	 * @return file if exists, null OW
	 */
	public File getFile(String checkSum) {
		File file = new File(savingDir + System.getProperty("file.separator") + checkSum);
		
		if (file.exists()) {
			return file;
		}
		return null;
	}

	/**
	 * delete file from server
	 * @param checkSum - file's checkSum
	 */
	public void deleteFile(String checkSum) {
		File file = new File(String.valueOf(savingDir + System.getProperty("file.separator") + checkSum));
		
		if (file.exists()) {
			file.delete();
		}
		//check if checkSum exists in data base
		if (isExists(checkSum)) {
			//delete it from data base
			DBManager.getDBManager().deleteCheckSum(checkSum);
		}
	}
}
